import os
import re


def rename_files_with_padded_numbers(root_path, recursive=False):
    """
    重命名文件夹中的文件，将文件名中第一个下划线前的数字补零到3位

    Args:
        root_path (str): 要处理的根目录路径
        recursive (bool): 是否递归处理子文件夹，默认为 False
    """
    # 遍历文件
    for entry in os.scandir(root_path):
        if entry.is_file():
            # 处理文件名
            old_name = entry.name
            # 使用正则匹配数字部分
            match = re.match(r'^(\d+)(?=_)', old_name)
            if match:
                num_str = match.group(1)
                # 补零到3位
                padded_num = num_str.zfill(3)
                # 构建新文件名
                new_name = old_name.replace(num_str, padded_num, 1)
                # 重命名文件
                old_path = os.path.join(root_path, old_name)
                new_path = os.path.join(root_path, new_name)
                try:
                    os.rename(old_path, new_path)
                    print(f"重命名成功: {old_name} -> {new_name}")
                except OSError as e:
                    print(f"重命名失败 {old_name}: {e}")

        # 递归处理子文件夹
        elif entry.is_dir() and recursive:
            rename_files_with_padded_numbers(entry.path, recursive)


# 使用示例
if __name__ == "__main__":
    target_folder = r"D:\selfData\study\2024 Langchain大模型AI应用与多智能体实战开发"  # 替换为实际路径
    rename_files_with_padded_numbers(target_folder, recursive=True)
